package com.xunshangwang.pinhaohuo.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.decorations.OffsetItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Address;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.ui.activities.address.AddAddressActivity;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;

/**
 * Created by xzp on 16/2/25.
 */
public class ChangeAddressActivity extends BaseActivity implements BaseRecyclerAdapter.OnItemClickListener,
        View.OnClickListener,SwipeRefreshLayout.OnRefreshListener{
    private RecyclerView mRecycler;
    private AddressAdapter mAdapter;
    private String mAddressId;
    private RefreshLayout mRefresh;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_address);
        mAddressId=getIntent().getStringExtra("addressId");
        mRecycler= (RecyclerView) this.findViewById(R.id.address_list);
        mRefresh= (RefreshLayout) this.findViewById(R.id.refresh_layout);
        mRefresh.setOnRefreshListener(this);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.addItemDecoration(new OffsetItemDecoration(this, R.dimen.address_list_offset) {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, getOffset() / 2, 0, getOffset() / 2);
            }
        });
        this.findViewById(R.id.add_address_btn).setOnClickListener(this);
        mAdapter=new AddressAdapter(this);
        mRecycler.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        },150);
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        String addressId=mAdapter.getList().get(position).getAddress_id();
        if(TextUtils.equals(addressId,mAddressId))
            return;
        Intent intent=new Intent();
        Bundle bundle=new Bundle();
        bundle.putSerializable("address",mAdapter.getList().get(position));
        intent.putExtras(bundle);
        setResult(RESULT_OK,intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        startActivityForResult(new Intent(this, AddAddressActivity.class),0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK)
            return;
        if(requestCode==0){
            if(mRefresh.isRefreshing())
                return;
            mRefresh.setRefreshing(true);
            onRefresh();
        }
    }

    @Override
    public void onRefresh() {
        requestAddressList();
    }
    private void requestAddressList(){
        HttpTool.get(this, "?g=Api&m=Weuser&a=addresses&token=" + getMainApplication().getToken(), new JsonHttpHandler<List<Address>>() {
            @Override
            public List<Address> parseData(JSONObject object) throws Throwable {
                return JSON.parseArray(object.getString("address_list"), Address.class);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Address> response) {
                mAdapter.setList(response);
            }
        });
    }
    private class AddressAdapter extends BaseRecyclerAdapter<Address>{
        public AddressAdapter(Context context) {
            super(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view=getLayoutInflater().inflate(R.layout.change_address_item,parent,false);
            return new AddressHolder(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            AddressHolder addressHolder= (AddressHolder) holder;
            Address address=getList().get(position);
            addressHolder.fullAddressText.setText(address.getFull_address());
            if(address.getMobile().length()==11){
                addressHolder.phoneText.setText(address.getMobile().substring(0,3)+"****"+address.getMobile().substring(7));
            }else
                addressHolder.phoneText.setText(address.getMobile());
            addressHolder.receiveNameText.setText(address.getReceive_name());
            if(TextUtils.equals(address.getAddress_id(),mAddressId)){
                addressHolder.checkBox.setChecked(true);
            }else {
                addressHolder.checkBox.setChecked(false);
            }
        }
        private class AddressHolder extends ClickableViewHolder{
            TextView receiveNameText,phoneText,fullAddressText;
            CheckBox checkBox;
            public AddressHolder(View itemView) {
                super(itemView);
                receiveNameText= (TextView) itemView.findViewById(R.id.receive_name_text);
                phoneText= (TextView) itemView.findViewById(R.id.mobile_phone_text);
                fullAddressText= (TextView) itemView.findViewById(R.id.full_address_text);
                checkBox= (CheckBox) itemView.findViewById(R.id.change_address_check_box);
            }
        }
    }
}
